package com.ruoyi.cases.utils.excel;


import java.awt.*;
import java.awt.Color;
import java.awt.font.TextAttribute;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFSimpleShape;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;





/**
 * 生成excel视图，xls格式 可用excel工具打开或者保存 由ViewController的return new ModelAndView(viewExcel, model)生成
 */

public class ExcelExportToFileUrlComplex {
    /**
     * 宽度
     */
    private  final int WIDTH = 360;
    /**
     * 高度
     */
    private  final int HEIGHT = 150;
    /**
     * 水印横向位置
     */
    private  int positionWidth = 80;
    /**
     * 水印纵向位置
     */
    private  int positionHeight = 30;
    /**
     * 水印文字 字体类型、风格、大小
     * microsoft-yahei、微软雅黑、宋体
     */
    private java.awt. Font font = new java.awt. Font("微软雅黑", java.awt. Font.PLAIN, 20);
    /**
     * 水印文字颜色
     * 最后一个参数（第四个参数）为水印透明度
     */
    private static Color color = new Color(0, 0, 0,125);

    /**
     * 创建Excel
     *
     * @param model    模板 fileName 文件名称 excelTitle excel标题 excelTitleClos excel标题合并列数 upNoFrame:表格上特殊文字 [[行号,列号(&分隔),文字(&分隔),合并单元格(起始行,结束行,起始列,结束列),行高(可不写)]]
     *                 downNoFrame:表格下特殊文字[[行号,列号(&分隔),文字(&分隔),合并单元格(起始行,结束行,起始列,结束列),行高(可不写)]] titleStarRows:表头起始行数 (数字) titleRows:数据起始行数(数字) titles0~titles+titleRows 表头数据(字符串[])
     *                 handClum:合并单元格(字符串[起始行,结束行,起始列,结束列]) scribing:col1,row1,col2,col2(数字[]) names 数据字段 list 数据
     * @param workbook Excel属性
     * @param request  请求
     * @param response 请求
     * @throws Exception 异常
     */
    private void gotoCreateExcel(Map model, Workbook workbook, HttpServletRequest request,
        HttpServletResponse response, List<String[][]> downList) throws Exception {
        String excelName =
            model.get("fileName") + "_" + DateUtils.dateTimeNow("yyyyMMddHHmmss") + ".xls";
        String fileType = String.valueOf(model.get("fileName"));
        // 设置response方式,使执行此controller时候自动出现下载页面,而非直接使用excel打开
        response.setContentType("APPLICATION/OCTET-STREAM;charset=UTF-8");
        String agent = request.getHeader("USER-AGENT");
        excelName = java.net.URLEncoder.encode(excelName, "UTF8");
        response.setHeader("Content-Disposition", "attachment; filename=" + excelName);
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        List<Map<String, String>> stuList = (List<Map<String, String>>) model.get("list");
        int index = 65520;
        int size = stuList.size();
        if (size > index) {
            int count = (size / index) + (size % index > 0 ? 1 : 0);
            for (int i = 1; i <= count; i++) {
                List<Map<String, String>> l = new ArrayList<Map<String, String>>();
                if (stuList.size() >= (i * index)) {
                    l = stuList.subList(index * (i - 1), index * i);
                } else {
                    l = stuList.subList(index * (i - 1), size);
                }
                if (l.size() > 0) {
                    addSheet(model, workbook, l, downList == null ? null : downList.get(i - 1));
                }
            }

        } else {
            // ExceptionUtils.serviceException("太多了");
            addSheet(model, workbook, stuList, downList == null ? null : downList.get(0));
        }
//        BufferedImage bufferedImage = createWaterMarkImage("吉高路桥集团建设有限公司");
//
//        int sheets = workbook.getNumberOfSheets();
//        //循环sheet给每个sheet添加水印
//        for (int i = 0; i < sheets; i++) {
//            Sheet sheet = workbook.getSheetAt(i);
//            //获取excel实际所占行
//            int row = sheet.getFirstRowNum() + sheet.getLastRowNum();
//            //获取excel实际所占列
//            int cell = sheet.getRow(sheet.getFirstRowNum()).getLastCellNum() + 1;
//            for (int n = 0; n < cell; n++) {
//                sheet.autoSizeColumn((short) n, false);
//            }
//            //根据行与列计算实际所需多少水印
//            putWaterMarkToExcel(workbook, sheet, bufferedImage, 0, 0, 2, 13, Integer.parseInt(String.valueOf(model.get("excelTitleClos"))) / 3 + 1, row / 13 + 1, 0, 0);
//            //excel加密只读
//            //sheet.protectSheet(UUID.randomUUID().toString());
//        }

        OutputStream os =  response.getOutputStream();
        workbook.write(os);
        os.flush();
        os.close();

    }

    private void addSheet(Map model, Workbook workbook, List<Map<String, String>> stuList, String[][] downNoFrame) {
        // 产生Excel表头
        HSSFSheet sheet = (HSSFSheet) workbook.createSheet();

        //设置列宽
        String columnWidths = (String) model.get("columnWidth");
        if (StringUtils.isNotBlank(columnWidths)) {
            String[] strings = columnWidths.split("&");
            for (String col : strings) {
                String[] split = col.split(",");
                sheet.setColumnWidth(Short.valueOf(split[0]), Integer.parseInt(split[1]) * 256);

            }
        }

        //excel标题
        String excelTitle = (String) model.get("excelTitle");
        int excelTitleClos =
            null != model.get("excelTitleClos") ? (int) model.get("excelTitleClos") : 0;
        //表格上特殊文字 [[行号,列号(&分隔),文字(&分隔),合并单元格(起始行,结束行,起始列,结束列)]]
        String excelTitleFontSize1 = (String) model.get("excelTitleFontSize");

        //字体处理方式
        Short excelTitleFontSize = Short
            .valueOf(StringUtils.isNotBlank(excelTitleFontSize1) ? excelTitleFontSize1 : "22");

        Font ztFont = getFont(workbook, excelTitleFontSize);
        ztFont.setBold(true);    //加粗

        //             ztFont.setUnderline(Font.U_DOUBLE);         // 添加（Font.U_SINGLE单条下划线/Font.U_DOUBLE双条下划线）
        //              ztFont.setStrikeout(true);                  // 是否添加删除线

        HSSFRow header = null;// 创建表头
        if (null != excelTitle) {
            //----------------标题样式---------------------
            HSSFCellStyle titleStyle = (HSSFCellStyle) workbook.createCellStyle();        //标题样式
            titleStyle.setAlignment(HorizontalAlignment.CENTER);
            titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);

            titleStyle.setFont(ztFont);
            //上边框
            titleStyle.setBorderTop(BorderStyle.THIN);
            //左边框
            titleStyle.setBorderLeft(BorderStyle.THIN);
            //右边框
            titleStyle.setBorderRight(BorderStyle.THIN);
            header = sheet.createRow(0);
            header.setHeight((short) 600);
            sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, excelTitleClos));
            HSSFCell cell = header.createCell(0);
            cell.setCellStyle(titleStyle);
            cell.setCellValue(excelTitle);
        }

        //字体
        String titleFontSizeStr = (String) model.get("titleFontSize");
        Short titleFontSize = Short
            .valueOf(StringUtils.isNotBlank(titleFontSizeStr) ? titleFontSizeStr : "12");
        Font tFont = getFont(workbook, excelTitleFontSize);

        tFont.setFontHeightInPoints(titleFontSize);
        CellStyle frameStyle = workbook.createCellStyle();
        frameStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        frameStyle.setFont(tFont);
        String[][] upNoFrame = (String[][]) model.get("upNoFrame");
        /*合并行*/
        String[][] hbTitle = (String[][]) model.get("hbTitle");
        if(null != hbTitle){
            for (int i = 0; i < hbTitle.length; i++) {
                String[] strings = hbTitle[i];
                sheet.addMergedRegion(new CellRangeAddress(Integer.parseInt(strings[0]), Integer.parseInt(strings[1]), Integer.parseInt(strings[2]), Integer.parseInt(strings[3])));
            }
        }

        //[[行号,列号(&分隔),文字(&分隔),合并单元格(起始行,结束行,起始列,结束列)]]
        if (null != upNoFrame) {
            for (int i = 0; i < upNoFrame.length; i++) {
                String[] strings = upNoFrame[i];
                header = sheet.createRow(Integer.parseInt(strings[0]));
                String[] clos = strings[1].split("&");
                String[] cloTitles = strings[2].split("&");
                String[] cloHand = strings[3].split("&");
                String height = null;
                if (strings.length == 5) {
                    height = strings[4];
                }
                if (null != height) {
                    header.setHeight(Short.parseShort(height));
                }
                for (int c = 0; c < clos.length; c++) {
                    String[] cloHands = cloHand[c].split(",");
                    sheet.addMergedRegion(new CellRangeAddress(Integer.parseInt(cloHands[0]),
                        Integer.parseInt(cloHands[1]), Integer.parseInt(cloHands[2]),
                        Integer.parseInt(cloHands[3])));
                    HSSFCell cell = header.createCell(Integer.parseInt(clos[c]));
                    cell.setCellStyle(frameStyle);
                    cell.setCellValue(cloTitles[5]);
                }
            }
        }

        //表格下特殊文字 [[行号,列号(&分隔),文字(&分隔),合并单元格(起始行,结束行,起始列,结束列)]]
        downNoFrame = downNoFrame == null ? (String[][]) model.get("downNoFrame") : downNoFrame;
        //[[行号,列号(&分隔),文字(&分隔),合并单元格(起始行,结束行,起始列,结束列)]]
        if (null != downNoFrame) {
            for (int i = 0; i < downNoFrame.length; i++) {
                String[] strings = downNoFrame[i];
                header = sheet.createRow(Integer.parseInt(strings[0]));
                String[] clos = strings[1].split("&");
                String[] cloTitles = strings[2].split("&");
                String[] cloHand = strings[3].split("&");
                String height = null;
                if (strings.length == 5) {
                    height = strings[4];
                }
                if (null != height) {
                    header.setHeight(Short.parseShort(height));
                }
                for (int c = 0; c < clos.length; c++) {
                    String[] cloHands = cloHand[c].split(",");
                    sheet.addMergedRegion(new CellRangeAddress(Integer.parseInt(cloHands[0]),
                        Integer.parseInt(cloHands[1]), Integer.parseInt(cloHands[2]),
                        Integer.parseInt(cloHands[3])));
                    HSSFCell cell = header.createCell(Integer.parseInt(clos[c]));
                    cell.setCellStyle(frameStyle);
                    cell.setCellValue(cloTitles[c]);
                }
            }
        }
        CellStyle titleCellStyle = getCellStyle(workbook);

        //表头行数
        int titleRows = (int) model.get("titleRows");
        //表头起始行数
        int titleStarRows =
            null != model.get("titleStarRows") ? (int) model.get("titleStarRows") : 0;
        for (int i = titleStarRows; i < titleRows; i++) {

            header = sheet.createRow(i);
            header.setHeight((short) 400);
            // 产生标题列  //名称
            String[] titles = (String[]) model.get("titles" + i);
            for (int n = 0; n < titles.length; n++) {
                HSSFCell cell = header.createCell(n);
                if (titles[n].contains("scribing")) {
                    //判断是否有斜线的如果有斜线那么格式特殊设置
                    CellStyle h = workbook.createCellStyle();
                    // 水平方bai向的对齐方du式zhi
//                    h.setAlignment(HSSFCellStyle.ALIGN_LEFT);
                    // 垂直方dao向的对齐方式
//                    h.setVerticalAlignment(HSSFCellStyle.VERTICAL_TOP);
                    //字符串
                    h.setDataFormat(HSSFDataFormat.getBuiltinFormat("TEXT"));
                    //上边框
                    h.setBorderTop(BorderStyle.THIN);
                    //左边框
                    h.setBorderLeft(BorderStyle.THIN);
                    h.setWrapText(true);
                    h.setFont(tFont);
                    cell.setCellStyle(h);
                    cell.setCellValue(new HSSFRichTextString(titles[n].replace("scribing", "")));
                } else {
                    titleFontSize = Short
                            .valueOf(StringUtils.isNotBlank(titleFontSizeStr) ? titleFontSizeStr : "16");
                    tFont = getFont(workbook, excelTitleFontSize);
                    tFont.setFontHeightInPoints(titleFontSize);
                    titleCellStyle.setFont(tFont);
                    cell.setCellStyle(titleCellStyle);
                    cell.setCellValue(titles[n]);

                }
            }
        }
        //合并单元格
        String[] handClum = (String[]) model.get("handClum");
        // 动态合并单元格
        if (null != handClum) {
            sheet.createRow(1);
            sheet.createRow(2);
            for(int i=1;i<=2;i++){
                frameStyle.setAlignment(HorizontalAlignment.CENTER);
                frameStyle.setBorderTop(BorderStyle.THIN);
                frameStyle.setBorderLeft(BorderStyle.THIN);
                frameStyle.setBorderBottom(BorderStyle.THIN);
                frameStyle.setBorderRight(BorderStyle.THIN);
                frameStyle.setWrapText(true);
                for(int j=0;j<((String[]) model.get("titles3")).length;j++){
                    sheet.getRow(i).createCell(j);
                    sheet.getRow(i).getCell(j).setCellStyle(frameStyle);

                }
            }
            sheet.getRow(1).setHeight(Short.parseShort(String.valueOf(650)));
            sheet.getRow(2).setHeight(Short.parseShort(String.valueOf(750)));
            for (int i = 0; i < handClum.length; i++) {
                // sheet.autoSizeColumn(i, true);
                String[] temp = handClum[i].split(",");
                Integer startrow = Integer.parseInt(temp[0]);
                Integer overrow = Integer.parseInt(temp[1]);
                Integer startcol = Integer.parseInt(temp[2]);
                Integer overcol = Integer.parseInt(temp[3]);
                sheet.addMergedRegion(new CellRangeAddress(startrow, overrow, startcol, overcol));
                sheet.getRow(Integer.parseInt(temp[0])).createCell(Integer.parseInt(temp[2])).setCellValue(temp[4]);
                /*设置样式*/
                sheet.getRow(Integer.parseInt(temp[0])).getCell(Integer.parseInt(temp[2])).setCellStyle(frameStyle);
            }
        }
        //划线 起始行 结束行
        int[] scribing = (int[]) model.get("scribing");
        //划线
        if (null != scribing) {
            sheet.setColumnWidth((short) scribing[0], 15 * 256);
            HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
            HSSFClientAnchor a = new HSSFClientAnchor(0, 0, 1023, 255, (short) scribing[0],
                scribing[1],
                (short) scribing[2], scribing[3]);
            HSSFSimpleShape shape1 = patriarch.createSimpleShape(a);
            shape1.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE);
            shape1.setLineStyle(HSSFSimpleShape.LINESTYLE_SOLID);
        }
        String[] names = (String[]) model.get("names");//字段

        CellStyle cellStyle = getCellStyle(workbook);
        Font font = getFont(workbook, (short) 12);
        cellStyle.setFont(font);
        ExcelExport.addCell(sheet, names, cellStyle, titleRows, stuList);
    }

    /**
     * 获取字体样式
     *
     * @param workbook           excel
     * @param excelTitleFontSize 字体大小
     * @return 字体样式
     */
    private Font getFont(Workbook workbook, Short excelTitleFontSize) {
        Font ztFont = workbook.createFont();
        ztFont.setItalic(false);                     // 设置字体为斜体字
        ztFont.setColor(Font.COLOR_NORMAL);            // 将字体设置为“红色”
        ztFont.setFontHeightInPoints(excelTitleFontSize);    // 将字体大小设置为16
        ztFont.setFontName("宋体");             // 将“宋体”字体应用到当前单元格上
        return ztFont;
    }

    /**
     * 格式
     *
     * @param workbook 格式数据
     * @return
     */
    private CellStyle getCellStyle(Workbook workbook) {
        CellStyle titleCellStyle = workbook.createCellStyle();
        titleCellStyle.setAlignment(HorizontalAlignment.CENTER);
        titleCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        titleCellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("TEXT"));//字符串
        titleCellStyle.setBorderBottom(BorderStyle.THIN); //下边框
        titleCellStyle.setBorderLeft(BorderStyle.THIN);//左边框
        titleCellStyle.setBorderTop(BorderStyle.THIN);//上边框
        titleCellStyle.setBorderRight(BorderStyle.THIN);//右边框
        return titleCellStyle;
    }

    /**
     * 创建Excel
     *
     * @param map                 map
     * @param httpServletRequest  请求
     * @param httpServletResponse 请求
     * @throws Exception 异常
     */
    public void buildExcelDocument(Map<String, Object> map, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws Exception {
        HSSFWorkbook workbook = new HSSFWorkbook();
        gotoCreateExcel1(map, workbook, null,null,null);
    }
    public void buildExcelDocument1(Map<String, Object> map, HttpServletRequest httpServletRequest,
                                   HttpServletResponse httpServletResponse) throws Exception {
        HSSFWorkbook workbook = new HSSFWorkbook();
        gotoCreateExcel(map, workbook, httpServletRequest,httpServletResponse,null);
    }

    /**
     * 创建Excel
     *
     * @param map                 map
     * @param httpServletRequest  请求
     * @param httpServletResponse 请求
     * @throws Exception 异常
     */
    public void buildExcelDocument(Map<String, Object> map, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse, List<String[][]> downList) throws Exception {
        HSSFWorkbook workbook = new HSSFWorkbook();
        gotoCreateExcel(map, workbook, httpServletRequest, httpServletResponse, (downList!=null&&downList.size()>0)?downList:null);
    }


    private SystemFile gotoCreateExcel1(Map model, Workbook workbook,  List<String[][]> downList,String savePath,String fileNamePart) throws Exception {
        SystemFile systemFile = new SystemFile();
        OutputStream out = null ;
        try{
            List<Map<String, String>> stuList = (List<Map<String, String>>) model.get("list");
            int index = 65520;
            int size = stuList.size();
            if (size > index) {
                int count = (size / index) + (size % index > 0 ? 1 : 0);
                for (int i = 1; i <= count; i++) {
                    List<Map<String, String>> l = new ArrayList<Map<String, String>>();
                    if (stuList.size() >= (i * index)) {
                        l = stuList.subList(index * (i - 1), index * i);
                    } else {
                        l = stuList.subList(index * (i - 1), size);
                    }
                    if (l.size() > 0) {
                        addSheet(model, workbook, l, downList == null ? null : downList.get(i - 1));
                    }
                }

            } else {
                addSheet(model, workbook, stuList, downList == null ? null : downList.get(0));
            }
            String filename = fileNamePart+new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
            String filePathPart = savePath+File.separator+new SimpleDateFormat("yyyy/MM/dd").format(new Date());
            File file = new File(filePathPart);
            if(!file.exists()){
                file.mkdirs();
            }
            out =new FileOutputStream(filePathPart+ File.separator + filename +".xls");
            systemFile.setName(filename +".xls");
            workbook.write(out);

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(out != null){
                out.flush();
                out.close();
            }
        }
        return systemFile;
    }

    public SystemFile saveExcelDocument(Map map, String savePath,String fileNamePart) throws Exception {
        HSSFWorkbook workbook = new HSSFWorkbook();
        SystemFile systemFile = gotoCreateExcel1(map, workbook,null, savePath,fileNamePart);
        return  systemFile;
    }

    public  BufferedImage createWaterMarkImage(String text) {
        // 获取bufferedImage对象创建空白图片
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_ARGB);
        // 获取Graphics2d对象创建图片画笔
        Graphics2D g = image.createGraphics();
        // 设置背景透明度
        image = g.getDeviceConfiguration().createCompatibleImage(WIDTH, HEIGHT, Transparency.TRANSLUCENT);
        g.dispose();
        g = image.createGraphics();
        // 设置对线段的锯齿状边缘处理
        // g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        // 文字处理
        AttributedString ats = new AttributedString(text);

        ats.addAttribute(TextAttribute.FONT, font, 0, text.length());
        //ats.addAttribute(TextAttribute.FONT, fontEncode, 0, text.length());

        AttributedCharacterIterator iter = ats.getIterator();
        // 水印旋转
        g.rotate(Math.toRadians(-15), (double) image.getWidth() / 2, (double) image.getHeight() / 2);
        // 设置水印文字颜色
        g.setColor(color);
        // 设置水印字体加粗
        g.setStroke(new BasicStroke(1));

        // 设置水印文字Font
        g.setFont(font);
        //g.setFont(fontEncode);

        // 设置水印文字透明度
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
        // 水印位置
        g.drawString(iter, positionHeight, positionWidth);
        // 释放资源
        g.dispose();
        return image;
    }

    /**
     * 为Excel打上水印工具函数 请自行确保参数值，以保证水印图片之间不会覆盖。
     *
     * @param wb              Excel Workbook
     * @param sheet           需要打水印的Excel
     * @param image           水印图片
     * @param startXCol       水印起始列
     * @param startYRow       水印起始行
     * @param betweenXCol     水印横向之间间隔多少列
     * @param betweenYRow     水印纵向之间间隔多少行
     * @param XCount          横向共有水印多少个
     * @param YCount          纵向共有水印多少个
     * @param waterMarkWidth  水印图片宽度为多少列
     * @param waterMarkHeight 水印图片高度为多少行
     * @throws IOException
     */
    public static void putWaterMarkToExcel(Workbook wb, Sheet sheet, BufferedImage image, int startXCol,
                                           int startYRow, int betweenXCol, int betweenYRow, int XCount, int YCount, int waterMarkWidth,
                                           int waterMarkHeight) throws IOException {
        // 加载图片
        ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
        if (null == image) {
            throw new RuntimeException("向Excel上面打印水印，读取水印图片失败！");
        }
        ImageIO.write(image, "png", byteArrayOut);

        // 开始打水印
        Drawing drawing = sheet.createDrawingPatriarch();

        // 按照共需打印多少行水印进行循环
        for (int yCount = 0; yCount < YCount; yCount++) {
            // 按照每行需要打印多少个水印进行循环
            for (int xCount = 0; xCount < XCount; xCount++) {
                // 创建水印图片位置
                int xIndexInteger = startXCol + (xCount * waterMarkWidth) + (xCount * betweenXCol);
                int yIndexInteger = startYRow + (yCount * waterMarkHeight) + (yCount * betweenYRow);
                /*
                 * 参数定义： 第一个参数是（x轴的开始节点）； 第二个参数是（是y轴的开始节点）； 第三个参数是（是x轴的结束节点）；
                 * 第四个参数是（是y轴的结束节点）； 第五个参数是（是从Excel的第几列开始插入图片，从0开始计数）；
                 * 第六个参数是（是从excel的第几行开始插入图片，从0开始计数）； 第七个参数是（图片宽度，共多少列）；
                 * 第8个参数是（图片高度，共多少行）；
                 */
                ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, xIndexInteger, yIndexInteger, xIndexInteger + waterMarkWidth, yIndexInteger + waterMarkHeight);
                Picture pic = drawing.createPicture(anchor,
                    wb.addPicture(byteArrayOut.toByteArray(), Workbook.PICTURE_TYPE_PNG));
                pic.resize();
            }
        }
    }
}
